<template>
  <div class="approver">
    <div
      v-if="
        route.query.name === '1' ||
        (route.query.name === '3' && route.query.task === '2') ||
        route.query.name === '2'
      "
      class="approver-add"
    >
      <div class="approver-item" v-for="(item, index) in approver" :key="index">
        <div class="approver-item-c">
          <el-avatar :src="url + item.avatar"></el-avatar>
          <el-tag
            type="success"
            closable
            @close="handleDelOpportunitiesApprover(index)"
          >
            {{ item.approvalName }}
          </el-tag>
          <div v-if="!isCc" style="font-weight: 500">
            第{{ item.approvalLevel }}级审批人
          </div>
        </div>
        <div v-if="!isCc && index !== approver.length - 1">
          <el-icon><Right /></el-icon>
        </div>

        <template
          v-if="
            !isCc &&
            typeof item.state === 'number' &&
            item.state !== 0 &&
            !isEdit
          "
        >
          <div>{{ item.byTheDate }}</div>
          <div>审批意见：{{ item.approvalOpinion }}</div>
        </template>
      </div>
    </div>
    <div v-else class="approver-details">
      <!-- {{detailsList}} {{1}} {{会议}} -->
      <div
        v-for="(item, index) in detailsList"
        :key="index"
        class="approver-item"
      >
        <div class="approver-item-c">
          <el-avatar :src="url + item.avatar"></el-avatar>
          <el-tag
            type="success"
            :closable="route.query.name !== '3'"
            @close="handleDelOpportunitiesApprover(index)"
          >
            {{ item.username || item.approvalName }}
          </el-tag>
        </div>
        <div v-if="!isCc && index !== detailsList.length - 1">
          <el-icon><Right /></el-icon>
        </div>
      </div>
    </div>
    <div v-if="!readonly">
      <el-button
        link
        type="primary"
        round
        v-if="hasButtonSave && mark"
        @click="
          approverDialog = true;
          handleAddPeople();
        "
        style="position: relative; top: -3px; left: -10px"
      >
        {{ isCc ? "添加抄送人" : "添加审批人" }}
      </el-button>
      <el-button
        link
        type="primary"
        round
        v-if="!mark && hasButtonSave"
        @click="
          approverDialog = true;
          handleAddPeopleS();
        "
        style="position: relative; top: -3px; left: -10px"
      >
        {{ !flag ? "添加记录人员" : "添加参会人员" }}
      </el-button>
    </div>
    <el-dialog
      :title="addTitle"
      v-if="approverDialog"
      v-model="approverDialog"
      append-to-body
      :close-on-click-modal="false"
      :before-close="handleClose"
      width="70%"
    >
      <div class="approver-inquiry">
        <el-form :model="groupParams" ref="ruleForm" style="display: flex">
          <el-form-item label="姓名">
            <el-input
              class="filter-item"
              v-model="groupParams.nickName"
              :clearable="true"
              placeholder="员工姓名"
            />
          </el-form-item>
          <el-form-item label="所属部门" style="margin-left: 10px">
            <el-cascader
              class="input-item"
              v-model="groupParams.deptId"
              :clearable="true"
              placeholder="所属部门"
              :props="dropdownprops"
              :options="dropdownList"
            >
            </el-cascader>
          </el-form-item>
          <el-form-item style="margin-left: 10px">
            <el-button type="primary" @click="onSubmit">查询</el-button>
            <el-button @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-table :data="groupList" header-cell-class-name="table-header-gray">
          <el-table-column type="index" label="序号" width="50" />
          <el-table-column label="用户名" prop="userName" align="center">
          </el-table-column>
          <el-table-column label="员工姓名" prop="nickName" align="center">
          </el-table-column>
          <el-table-column
            label="部门"
            prop="dept.deptName"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="100"
          >
            <template #default="scope">
              <el-button
                type="primary"
                @click="handleChooseapprover(scope.row)"
                v-if="!scope.row.check"
                >选择</el-button
              >
              <el-button
                type="danger"
                @click="handleCancelapprover(scope.row, scope.$index)"
                v-if="scope.row.check"
                >取消</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end" style="margin-top: 10px">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            :total="total"
          ></el-pagination>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import headerImg from "@/assets/images/default-header.png";
import { onMounted, reactive, watch } from "vue";
import { Search } from "@element-plus/icons-vue";
import {
  selectsPeople,
  deptNameApi,
  selectsPeoples,
  deptTreeSelect,
  listUser,
} from "@/api/project/conversion";

import { useRouter, useRoute } from "vue-router";
import { rowKey } from "element-plus/es/components/table-v2/src/common";
const route = useRoute();

const stateNameArr = ["待审核", "审核通过", "审核驳回"];
const headerImgSrc = ref(headerImg);
const addTitle = ref("添加审批人");
const url = import.meta.env.VITE_APP_BASE_API;
const router = useRouter();

const groupParams = reactive({
  nickName: "", //员工姓名
  deptId: "", //所属部门
});
const groupList = ref([]);
const hasButtonSave = ref(false);

// 1.按钮保存隐藏
const hasButton = () => {
  if (route.query.name === "3") {
    if (route.query.task === "2") {
      hasButtonSave.value = true;
    } else {
      hasButtonSave.value = false;
    }
  } else {
    hasButtonSave.value = true;
  }
};
const check = ref(true);

const approverDialog = ref(false);

const dropdownList = ref([]);
// 所属部门名称
const deptNameRole = async () => {
  try {
    let params = {};
    const response = await deptNameApi(params);
    if (response.code === 200 && response.data.length >= 0) {
      dropdownList.value = response.data;
    }
  } catch (err) {
    console.log(err);
  }
};

const approver = ref([]);
let dropdownprops = {
  value: "deptId",
  label: "deptName",
  emitPath: false,
};

const props = defineProps({
  // 请求用户列表的函数
  getUserFn: {
    type: Function,
    default: () => {},
  },

  typeId: {
    default: undefined,
  },
  // 是否为抄送
  isCc: {
    type: Boolean,
    default: false,
  },
  // 角色按钮是否显示
  role: {
    type: Boolean,
    default: false,
  },
  // 回显的话为true
  readonly: {
    type: Boolean,
    default: false,
  },
  // 是否为编辑
  isEdit: {
    type: Boolean,
    default: false,
  },
  approverList: {
    type: Array,
    default: () => [],
  },
  flag: {
    type: Boolean,
    default: false,
  },
  mark: {
    type: Boolean,
    default: true,
  },
});

const handleAddPeople = () => {
  if (props.isCc) {
    addTitle.value = "添加抄送人";
  } else {
    addTitle.value = "添加审批人";
  }
};

const handleAddPeopleS = () => {
  if (props.flag) {
    addTitle.value = "添加参会人员";
  } else {
    addTitle.value = "添加记录人员";
  }
};

let pageNum = ref(1);
let pageSize = ref(10);
let total = ref(0);

const emit = defineEmits([
  "handleChooseapprover",
  "handleCancelapprover",
  "approverData",
]);
const deptOptions = ref(undefined);
const { proxy } = getCurrentInstance();
const userList = ref([]);

/** 查询部门下拉树结构 */
// function getDeptTree() {
//   deptTreeSelect().then((response) => {
//     deptOptions.value = response.data;
//   });
// }

// const queryParams = reactive({
//   pageNum: 1,
//   pageSize: 10,
//   userName: undefined,
//   phonenumber: undefined,
//   status: undefined,
//   deptId: undefined,
// });

/** 查询用户列表 */
// function getList() {
//   // loading.value = true;
//   listUser(queryParams.value).then(
//     (res) => {
//       // loading.value = false;
//       userList.value = res.rows;
//       total.value = res.total;
//     }
//   );
// }

// 会议查询
const approverData = async () => {
  try {
    let params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      nickName: groupParams.nickName,
      deptId: groupParams.deptId,
    };
    const response = await selectsPeople(params);
    if (response.code === 200 && response.rows.length >= 0) {
      groupList.value = response.rows;
      //有已选择数据：找到相同的数据，将已选择数据中的状态赋值给弹窗列表的状态
      if (
        route.query.name === "1" ||
        (route.query.name === "3" && route.query.task === "2") ||
        route.query.name === "2"
      ) {
        if (approver.value.length) {
          // 找到相同的数据的数组
          approver.value.forEach((item) => {
            const selectUser = groupList.value.find(
              (it) => it.userId === item.userId
            );
            // @ts-ignore
            if (selectUser) {
              selectUser.check = true;
            }
          });
        }
      } else {
        if (detailsList.value.length) {
          // 找到相同的数据的数组
          detailsList.value.forEach((item) => {
            const selectUser = groupList.value.find(
              (it) => it.userId === item.userId
            );
            // @ts-ignore
            if (selectUser) {
              selectUser.check = true;
            }
          });
        }
      }

      total.value = Number(response.total);
    }
  } catch (err) {
    console.log(err);
  }
};
// 审批人查询
const approverDatas = async () => {
  try {
    let params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      nickName: groupParams.nickName,
      deptId: groupParams.deptId,
    };
    const response = await selectsPeoples(params);

    if (response.code === 200 && response.rows.length >= 0) {
      groupList.value = response.rows;
      //有已选择数据：找到相同的数据，将已选择数据中的状态赋值给弹窗列表的状态
      if (
        route.query.name === "1" ||
        (route.query.name === "3" && route.query.task === "2") ||
        route.query.name === "2"
      ) {
        if (approver.value.length) {
          // 找到相同的数据的数组
          approver.value.forEach((item) => {
            const selectUser = groupList.value.find(
              (it) => it.userId === item.userId
            );
            // @ts-ignore
            if (selectUser) {
              selectUser.check = true;
            }
          });
        }
      } else {
        if (detailsList.value.length) {
          // 找到相同的数据的数组
          detailsList.value.forEach((item) => {
            // console.log(groupList.value,'--groupList.value--')
            const selectUser = groupList.value.find(
              (it) => it.userId === item.userId
            );
            // console.log(selectUser,'--selectUser--')
            // @ts-ignore
            if (selectUser) {
              selectUser.check = true;
            }
          });
        }
      }

      total.value = Number(response.total);
    }
  } catch (err) {
    console.log(err);
  }
};

// 查询
const onSubmit = () => {
  // if (route.path === "/myProject/information-info/addMeeting") {
  //   approverData();
  // } else {
  //   approverDatas();
  // }
  approverDatas();
};

// 重置
const reset = () => {
  groupParams.nickName = "";
  groupParams.deptId = "";
  approverDatas();
};

const handleSizeChange = (valueSise) => {
  pageSize.value = valueSise;
  approverDatas();
};

const handleCurrentChange = (valuePage) => {
  pageNum.value = valuePage;
  approverDatas();
};

// 移除人员
const handleDelOpportunitiesApprover = (index) => {
  if (
    route.query.name === "1" ||
    (route.query.name === "3" && route.query.task === "2") ||
    route.query.name === "2"
  ) {
    // 删除当前条数据
    approver.value.splice(index, 1);
    approver.value.forEach((item, i) => {
      item.approvalLevel = i + 1;
    });
    emit("handleChooseapprover", approver.value);
  } else {
    detailsList.value.splice(index, 1);
    // 级别
    detailsList.value.forEach((item, i) => {
      item.approvalLevel = i + 1;
    });

    emit("handleChooseapprover", detailsList.value);
  }
};

// 审批人取消
const handleCancelapprover = (row) => {
  row.check = false;
  // 删除当前条数据
  if (
    route.query.name === "1" ||
    (route.query.name === "3" && route.query.task === "2") ||
    route.query.name === "2"
  ) {
    const index = approver.value.findIndex((it) => it.userId === row.userId);
    approver.value.splice(index, 1);
  } else {
    const index = detailsList.value.findIndex((it) => it.userId === row.userId);
    console.log(index);
    // @ts-ignore
    detailsList.value.splice(index, 1);
  }

  emit("handleCancelapprover");
};

// 审批人选择
const handleChooseapprover = (row) => {
  // console.log(row, "---row---");
  row.check = true;
  if (
    route.query.name === "1" ||
    (route.query.name === "3" && route.query.task === "2") ||
    route.query.name === "2"
  ) {
    approver.value.push({
      approvalLevel: approver.value ? approver.value.length + 1 : 1,
      approvalName: row.nickName,
      userId: row.userId,
      avatar: row.avatar,
    });
    let userIds = approver.value.map((item) => item.userId);
    emit("handleChooseapprover", userIds);
  } else {
    detailsList.value.push({
      approvalLevel: detailsList.value ? detailsList.value.length + 1 : 1,
      approvalName: row.nickName,
      userId: row.userId,
      avatar: row.avatar,
    });
    emit("handleChooseapprover", detailsList.value);
  }
};

// 关闭
const handleClose = () => {
  approverDialog.value = false;
  groupParams.nickName = "";
  groupParams.deptId = "";
};

const detailsApprover = ref([]);
const detailsList = ref([]);

// 监听变化
watchEffect(async () => {
  detailsApprover.value = props.approverList;

  // 默认审批人列表数据
  detailsList.value = detailsApprover.value.map((item, index) => ({
    approvalLevel: index + 1,
    userId: Number(item.userId),
    approvalName: item.userName || item.approvalName,
    avatar: item.avatar,
  }));
  // if (route.path === "/myProject/information-info/addMeeting") {
  //   approverDatas();
  // } else {
  //   approverDatas();
  // }
  approverDatas();
});

onMounted(async () => {
  hasButton();
  // await getDeptTree();
  // await getList();
  await approverDatas();
  await deptNameRole();
});
</script>
<style lang="scss" scoped>
.approver {
  display: flex;
}
.approver-add {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  background: #fff;
  .approver-item {
    display: flex;
    justify-content: space-between;
    .approver-item-c {
      padding: 0 10px;
      text-align: center;
      display: flex;
      flex-direction: column;
      align-items: center;
      & > * {
        margin: 5px 0;
      }
    }
  }

  :deep(.el-form-item__content) {
    display: flex;
  }
}

.approver-details {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  .approver-item {
    display: flex;
    justify-content: space-between;
    .approver-item-c {
      padding: 0 10px;
      text-align: center;
      display: flex;
      flex-direction: column;
      align-items: center;
      & > * {
        margin: 5px 0;
      }
    }
  }

  :deep(.el-form-item__content) {
    display: flex;
  }
}
</style>
